package com.css.zfzx.sjcj.modules.qhdrillhistogram.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.zfzx.sjcj.common.utils.BeanUtil;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.ServerUtil;
import com.css.zfzx.sjcj.modules.qhdrillhistogram.repository.QhDrillHistogramNativeRepository;
import com.css.zfzx.sjcj.modules.qhdrillhistogram.repository.QhDrillHistogramRepository;
import com.css.zfzx.sjcj.modules.qhdrillhistogram.repository.entity.QhDrillHistogramEntity;
import com.css.zfzx.sjcj.modules.qhdrillhistogram.service.QhDrillHistogramService;
import com.css.zfzx.sjcj.modules.qhdrillhistogram.viewobjects.QhDrillHistogramQueryParams;
import com.css.zfzx.sjcj.modules.qhdrillhistogram.viewobjects.QhDrillHistogramVO;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.modules.qhdrilloverview.repository.QhDrillOverviewRepository;
import com.css.zfzx.sjcj.modules.qhdrilloverview.repository.entity.QhDrillOverviewEntity;
import com.css.zfzx.sjcj.modules.qhdrilloverview.viewobjects.QhDrillOverviewVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author aa
 * @date 2020-11-11
 */
@Slf4j
@Service
public class QhDrillHistogramServiceImpl implements QhDrillHistogramService {

	@Autowired
    private QhDrillHistogramRepository qhDrillHistogramRepository;
    @Autowired
    private QhDrillHistogramNativeRepository qhDrillHistogramNativeRepository;
    @Autowired
    private QhDrillOverviewRepository qhDrillOverviewRepository;

    @Override
    public JSONObject queryQhDrillHistograms(QhDrillHistogramQueryParams queryParams, int curPage, int pageSize) {
        Page<QhDrillHistogramEntity> qhDrillHistogramPage = this.qhDrillHistogramNativeRepository.queryQhDrillHistograms(queryParams, curPage, pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(qhDrillHistogramPage);
        return jsonObject;
    }


    @Override
    public QhDrillHistogramEntity getQhDrillHistogram(String id) {
        QhDrillHistogramEntity qhDrillHistogram = this.qhDrillHistogramRepository.findById(id).orElse(null);
         return qhDrillHistogram;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public QhDrillHistogramEntity saveQhDrillHistogram(QhDrillHistogramEntity qhDrillHistogram) {
        String uuid = UUIDGenerator.getUUID();
        qhDrillHistogram.setId(uuid);
        qhDrillHistogram.setCreateUser(PlatformSessionUtils.getUserId());
        qhDrillHistogram.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        qhDrillHistogram.setIsValid("1");
        qhDrillHistogram.setReviewStatus("0");
        qhDrillHistogram.setQualityinspectionStatus("0");
        this.qhDrillHistogramRepository.save(qhDrillHistogram);
        return qhDrillHistogram;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public QhDrillHistogramEntity updateQhDrillHistogram(QhDrillHistogramEntity qhDrillHistogram) {
        qhDrillHistogram.setUpdateUser(PlatformSessionUtils.getUserId());
        qhDrillHistogram.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.qhDrillHistogramRepository.save(qhDrillHistogram);
        return qhDrillHistogram;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteQhDrillHistograms(List<String> ids) {
        List<QhDrillHistogramEntity> qhDrillHistogramList = this.qhDrillHistogramRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(qhDrillHistogramList) && qhDrillHistogramList.size() > 0) {
            for(QhDrillHistogramEntity qhDrillHistogram : qhDrillHistogramList) {
//                this.qhDrillHistogramRepository.delete(qhDrillHistogram);
                qhDrillHistogram.setUpdateUser(PlatformSessionUtils.getUserId());
                qhDrillHistogram.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                qhDrillHistogram.setIsValid("0");
                this.qhDrillHistogramRepository.save(qhDrillHistogram);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitQhDrillHistograms(String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        List<QhDrillHistogramEntity> qhDrillHistogramList = this.qhDrillHistogramRepository.findAllById(idList);
        if(!PlatformObjectUtils.isEmpty(qhDrillHistogramList) && qhDrillHistogramList.size() > 0) {
            for(QhDrillHistogramEntity qhDrillHistogram : qhDrillHistogramList) {
                qhDrillHistogram.setUpdateUser(PlatformSessionUtils.getUserId());
                qhDrillHistogram.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                qhDrillHistogram.setReviewStatus("1");
                this.qhDrillHistogramRepository.save(qhDrillHistogram);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public String importExcel(MultipartFile file) {
        return this.importExcel(file,new HashMap<>());
    }

    @Override
    public String importExcel(MultipartFile file, Map<String,String> attachmentMap) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            params.setTitleRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<QhDrillHistogramVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), QhDrillHistogramVO.class, params);
            List<QhDrillHistogramVO> list = result.getList();
            //处理附件信息
            for(QhDrillHistogramVO dhVo : list) {
                String attachment = dhVo.getAttachment();
                dhVo.setAttachment(attachmentMap.containsKey(attachment) ? attachmentMap.get(attachment) : attachment);
            }
            // 批量新增
            this.saveExcel(list);
            returnMsg.append("成功导入" + result.getList().size() + "条，失败" + result.getFailList().size() + "条<br/>");
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<QhDrillHistogramVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    QhDrillHistogramVO areaVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + areaVO.getRowNum() + "行" + areaVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "导入失败，请检查数据正确性";
        }
    }

    @Override
    public String exportExcel(String ids, HttpServletResponse response) {
        List<String> idList = Arrays.asList(ids.split(","));
        List<QhDrillHistogramEntity> areaEntities = this.qhDrillHistogramRepository.findAllById(idList);

        return exportExcel(areaEntities,response);
    }

    @Override
    public String exportExcel(List<QhDrillHistogramEntity> entities, HttpServletResponse response)
    {
        try {
            // 深拷贝
            ArrayList<QhDrillHistogramVO> vos = new ArrayList<>();
            for (QhDrillHistogramEntity areaEntity : entities) {
                QhDrillHistogramVO vo = new QhDrillHistogramVO();
                BeanUtils.copyProperties(areaEntity, vo);
                vos.add(vo);
            }
            // 导出
            EasyPoiExcelUtil.exportExcel(vos, "钻孔综合柱状图采集", "钻孔综合柱状图", QhDrillHistogramVO.class, "钻孔综合柱状图.xls", response);
            return "导出成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    private void saveExcel(List<QhDrillHistogramVO> list) {
        for (int i = 0; i < list.size(); i++) {
            //QhDrillHistogramEntity areaEntity = new QhDrillHistogramEntity();
            QhDrillHistogramVO areaVO = list.get(i);
            QhDrillHistogramEntity areaEntity = qhDrillHistogramRepository.findById(areaVO.getId()).get();
            // 将VO数据映射拷贝到库表中
            BeanUtil.copyPropertiesIgnoreNull(areaVO, areaEntity);
            updateQhDrillHistogram(areaEntity);
        }
    }

    @Override
    public JSONObject checkCoordinate(String ids) {
        List<String> codeList = new ArrayList<>();
        List<String> idList = Arrays.asList(ids.split(","));
        List<QhDrillHistogramEntity> qhDrillHistogramList = this.qhDrillHistogramRepository.findAllById(idList);
        boolean hadData = !PlatformObjectUtils.isEmpty(qhDrillHistogramList) && qhDrillHistogramList.size() > 0;
        if(hadData) {
            for(QhDrillHistogramEntity qhDrillHistogram : qhDrillHistogramList) {
                String drillCode = qhDrillHistogram.getDrillCode();
                codeList.add(drillCode);
            }
        }

        List<String> drillHistogramCodes = new ArrayList<>();
        if(hadData && codeList.size() > 1) {
             List<QhDrillOverviewEntity> qhDrillOverviewsList = qhDrillOverviewRepository.findByIsValidAndDrillCodeIn("1",codeList);
            if(!PlatformObjectUtils.isEmpty(qhDrillOverviewsList) && qhDrillOverviewsList.size() > 0) {
                for(QhDrillOverviewEntity qhDrillOverview : qhDrillOverviewsList) {
                    String drillCodeOE = qhDrillOverview.getDrillCode();
                    String drillXOE = qhDrillOverview.getDrillX();
                    String drillYOE = qhDrillOverview.getDrillY();

                    for(QhDrillHistogramEntity qhDrillHistogram : qhDrillHistogramList) {
                        String drillCodeHE = qhDrillHistogram.getDrillCode();
                        String drillXHE = qhDrillHistogram.getDrillX();
                        String drillYHE = qhDrillHistogram.getDrillY();
                        if(drillCodeHE.equals(drillCodeOE) && (!drillXHE.equals(drillXOE) || !drillYHE.equals(drillYOE))) {
                            String id = qhDrillHistogram.getId();
                            drillHistogramCodes.add(id);
                        }
                    }
                }
            }
        }

        JSONObject json = new JSONObject();
        json.put("data",drillHistogramCodes);
        if(drillHistogramCodes.size() > 0) {
            json.put("message", "共" + drillHistogramCodes.size() + "条数据校验未通过");
        } else {
            json.put("message", "数据校验通过");
        }

        return json;
    }

    private void setCheckFields(Map<String,String> methods){
        methods.put("drillCode", "钻孔编号");
        methods.put("projectName", "工程名称");
        methods.put("orificeElevation", "孔口高程");
        methods.put("drillX", "钻孔坐标格网X值");
        methods.put("drillY", "钻孔坐标格网Y值");
        methods.put("commencementDate", "开工日期");
        methods.put("completionDate", "竣工日期");
        methods.put("stableWaterDepth", "稳定水位深度");
        methods.put("formationCode", "地层编号");
        methods.put("formationCauseAge", "地层成因年代");
        methods.put("bottomElevation", "层底高程");
        methods.put("bottomDepth", "层底深度");
        methods.put("layerThickness", "层厚");
        methods.put("columnarDiagram", "比例尺为不小于1：500的柱状图示");
        methods.put("geotechnicalName", "岩土名称");
        methods.put("geotechnicalCharacteristics", "岩土特征");
        methods.put("sampleDepthCode", "取样深度及编号");
        methods.put("standardPenetrationNum", "标准贯入实验实测值");
        methods.put("standardPenetrationDepth", "标准贯入实验实验深度");
        methods.put("province", "省");
        methods.put("city", "市");
        methods.put("area", "区/县");
    }

    @Override
    public JSONObject dataQualityCheck(List<QhDrillHistogramEntity> qhDrillHistogramList)
    {
        JSONObject res = new JSONObject();

        try {
            if(PlatformObjectUtils.isEmpty(qhDrillHistogramList) || qhDrillHistogramList.size() < 1) {
                return res;
            }

            Map<String, JSONObject> idBottomMap = new HashMap<>();
            String bottomDepthField = "bottomDepth";
            String layerThicknessField = "layerThickness";
            String bottomDepthIndexStr = "bottomDepthIndex";
            String layerThicknessIndexStr = "layerThicknessIndex";
            int bottomDepthIndex = 0;
            int layerThicknessIndex = 0;
            for (QhDrillHistogramEntity qhDrillHistogram : qhDrillHistogramList) {
                //检查字段值不为空
                StringBuilder errorMsg = new StringBuilder();
                Map<String, String> methods = new HashMap<>();
                setCheckFields(methods);

                ServerUtil.checkFieldNull(qhDrillHistogram, methods, errorMsg);

                float bottomDepth = Float.parseFloat(qhDrillHistogram.getBottomDepth());
                float layerThickness = Float.parseFloat(qhDrillHistogram.getLayerThickness());

                //层底深度不超过1000
                if (Float.isNaN(bottomDepth) || bottomDepth > 1000) {
                    ServerUtil.addErrorMsg(errorMsg, "层底深度", "大于1000");
                }

                //写入系统质检原因
                String strErrorMsg = errorMsg.toString();
                if(!strErrorMsg.isEmpty()) {
                    qhDrillHistogram.setQualityinspectionComments(strErrorMsg);
                    qhDrillHistogram.setQualityinspectionStatus("1");
                    qhDrillHistogram.setQualityinspectionResult("0");
                    this.updateQhDrillHistogram(qhDrillHistogram);

                    res.put(qhDrillHistogram.getId(),strErrorMsg);
                } else {
                    qhDrillHistogram.setQualityinspectionComments("");
                    qhDrillHistogram.setQualityinspectionStatus("1");
                    qhDrillHistogram.setQualityinspectionResult("1");
                    this.updateQhDrillHistogram(qhDrillHistogram);
                }

                //记录最大层底深度 层厚叠加
                if (!idBottomMap.containsKey(qhDrillHistogram.getDrillCode())) {
                    JSONObject jsonOb = new JSONObject();
                    idBottomMap.put(qhDrillHistogram.getDrillCode(), jsonOb);
                    jsonOb.put(bottomDepthField, 0);
                    jsonOb.put(layerThicknessField, 0);
                }
                JSONObject json = idBottomMap.get(qhDrillHistogram.getDrillCode());
                float maxBottomDepth = json.getFloat(bottomDepthField);
                if (!Float.isNaN(bottomDepth) && maxBottomDepth < bottomDepth) {
                    json.put(bottomDepthField, bottomDepth);
                    json.put(bottomDepthIndexStr,bottomDepthIndex);
                }
                if (!Float.isNaN(layerThickness)) {
                    float temp = json.getFloat(layerThicknessField);
                    json.put(layerThicknessField, layerThickness + temp);
                    json.put(layerThicknessIndexStr,layerThicknessIndex);
                }

                ++bottomDepthIndex;
                ++layerThicknessIndex;
            }

            for(Map.Entry<String,JSONObject> entry : idBottomMap.entrySet()){
                String code = entry.getKey();
                JSONObject value = entry.getValue();
                List<QhDrillOverviewEntity> qhDrillOverviews = qhDrillOverviewRepository.findByIsValidAndDrillCode("1", code);
                if(qhDrillOverviews.size() != 1) {
                    continue;
                }

                QhDrillOverviewEntity qhDrillOverview = qhDrillOverviews.get(0);
                float drillDepth = Float.parseFloat(qhDrillOverview.getDrillDepth());

                if(value.getFloat(bottomDepthField) != drillDepth){
                    int index = value.getInteger(bottomDepthIndexStr);
                    QhDrillHistogramEntity qhDrillHistogram = qhDrillHistogramList.get(index);

                    StringBuilder builder = new StringBuilder(qhDrillHistogram.getQualityinspectionComments());
                    ServerUtil.addErrorMsg(builder,"层底深度","最后一层深度应当与终孔深度一致");

//                    String tempStr = res.getString(qhDrillHistogram.getId());
//                    tempStr = tempStr == null ? "" : tempStr;
                    String tempStr = builder.toString();

                    qhDrillHistogram.setQualityinspectionComments(tempStr);
                    qhDrillHistogram.setQualityinspectionStatus("1");
                    qhDrillHistogram.setQualityinspectionResult("0");
                    this.updateQhDrillHistogram(qhDrillHistogram);

                    res.put(qhDrillHistogram.getId(),tempStr);
                }
                if(value.getFloat(layerThicknessField) != drillDepth){
                    int index = value.getInteger(layerThicknessIndexStr);
                    QhDrillHistogramEntity qhDrillHistogram = qhDrillHistogramList.get(index);

                    StringBuilder builder = new StringBuilder(qhDrillHistogram.getQualityinspectionComments());
                    ServerUtil.addErrorMsg(builder,"层厚","层厚的叠加应当为层底深度");

//                    String tempStr = res.getString(qhDrillHistogram.getId());
//                    tempStr = tempStr == null ? "" : tempStr;
                    String tempStr = builder.toString();

                    qhDrillHistogram.setQualityinspectionComments(tempStr);
                    qhDrillHistogram.setQualityinspectionStatus("1");
                    qhDrillHistogram.setQualityinspectionResult("0");
                    this.updateQhDrillHistogram(qhDrillHistogram);

                    res.put(qhDrillHistogram.getId(),tempStr);
                }
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }

        return res;
    }

    @Override
    public JSONObject dataQualityCheck(String drillCodes) {
        List<String> idList = Arrays.asList(drillCodes.split(","));
        List<QhDrillHistogramEntity> qhDrillHistogramList = this.qhDrillHistogramRepository.findByIsValidAndDrillCodeIn("1",idList);

        return dataQualityCheck(qhDrillHistogramList);
    }

    @Override
    public QhDrillHistogramEntity inspectionPassed(QhDrillHistogramEntity qhDrillHistogram) {
        qhDrillHistogram.setQualityinspectionStatus(ServerUtil.getQcFieldString());
        qhDrillHistogram.setQualityinspectionResult("1");
        return this.updateQhDrillHistogram(qhDrillHistogram);
    }

    @Override
    public QhDrillHistogramEntity inspectionFailed(QhDrillHistogramEntity qhDrillHistogram) {
        qhDrillHistogram.setQualityinspectionStatus(ServerUtil.getQcFieldString());
        qhDrillHistogram.setQualityinspectionResult("0");
        return this.updateQhDrillHistogram(qhDrillHistogram);
    }
}
